package com.itboye.pondteam.utils;

import android.os.Handler;
import android.os.Message;

import com.google.gson.Gson;
import com.itboye.pondteam.bean.SearchDeviceInfo;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketException;
import java.net.UnknownHostException;


/**
 * Created by 赵武 on 2015/3/12.
 * 日期：2015-05-05
 * 1. 丢弃无密码的广播
 */
public class AqDeviceFind {
	public DatagramSocket mUdpSocket = null;
	public int mUdpPort = 0;
	public Thread mThread = null;
	private boolean mThreadIsRun = false;
	public Handler mHandler;
	private MulticastSocket sender;
	private SearchDeviceInfo searchDeviceInfo;
	String req = "{\"req\":\"device_info\"}";
	int port = 0;
	private Runnable runnable = new Runnable() {
		@Override
		public void run() {
			handler.sendEmptyMessage(1);
		}
	};

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			new udpBroadCast(req, port).start();
			handler.postDelayed(runnable, 1000);
		}
	};
	private Thread myThread = null;

	public AqDeviceFind(Handler handler) {
		mHandler = handler;
	}

	public boolean isRun() {
		if (mThread == null) {
			return false;
		}
		return mThreadIsRun;
	}

	public boolean isRunMyThread() {
		if (mThread == null) {
			return false;
		}
		return mThreadIsRun;
	}

	/**
	 * 开始查找设备
	 *
	 * @param port 监听端口，默认15151
	 * @return 已经运行或者运行失败返回false，成功返回true
	 */
	public boolean start(int port) {
		this.port = port;
//        if (!isRunMyThread()) {
//            myThread = new Thread(runnable);
//            myThread.start();
//        }
		new udpBroadCast(req, port).start();
		return true;
	}

	DatagramPacket dj;
	Gson gson = new Gson();

	/* 发送udp多播 */
	private class udpBroadCast extends Thread {
		InetAddress group = null;
		byte[] data = new byte[1024];
		int port = 0;

		public udpBroadCast(String dataString, int port) {
			data = dataString.getBytes();
			this.port = port;
		}

		@Override
		public void run() {
			System.out.println(">>>发现设备1");
//            while (true) {
//                try {
//                    try {
//                        sender = new MulticastSocket();
//                        group = InetAddress.getByName("255.255.255.255");
//                        dj = new DatagramPacket(data, data.length, group, port);
//                        sender.send(dj);
////				sender.close();
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
////                    sender = new MulticastSocket();
//                    DatagramPacket dpIn = null;
//                    byte[] bufferIn = new byte[256];
//                    dpIn = new DatagramPacket(bufferIn, bufferIn.length);
//                    sender.receive(dpIn);
//                    System.out.println(">>>发现设备4");
//                    String packData = new String(bufferIn, 0, bufferIn.length, "gb2312");
//                    searchDeviceInfo = gson.fromJson(packData.replaceAll("\u0000", ""), SearchDeviceInfo.class);
//                    Message message = new Message();
//                    message.obj = searchDeviceInfo;
//                    sendMessage(message);
//                    sender.close();
//                    SystemClock.sleep(3000);
//                } catch (Exception e) {
//                    sender.close();
//                    SystemClock.sleep(3000);
//                }
//            }
			// 变量
//            byte[] datar = new byte[1024];

			// 接收循环
			while (!Thread.currentThread().isInterrupted()) {
				System.out.println("发现设备3");
				DatagramPacket dpr = null;
				// 创建UDP
				try {

					group = InetAddress.getByName("255.255.255.255");
					dpr = new DatagramPacket(data, data.length, group, port);
//                    dpr = new DatagramPacket(data, data.length);
					mUdpSocket = new DatagramSocket();
					mUdpSocket.setBroadcast(true);
					mUdpSocket.setSoTimeout(2000);
					try {
						mUdpSocket.send(dpr);
					} catch (IOException e) {
						e.printStackTrace();
					}

					System.out.println("发现设备2");
				} catch (SocketException e) {
//                    mThread.interrupt();
				} catch (UnknownHostException e) {
//                    mThread.interrupt();
				}
				try {
					byte[] bufferIn = new byte[256];
					DatagramPacket  dpIn = new DatagramPacket(bufferIn, bufferIn.length);
					mUdpSocket.receive(dpIn);
					String packData = new String(bufferIn, 0, bufferIn.length, "gb2312");
					packData=packData.replaceAll("\u0000", "");
					searchDeviceInfo = gson.fromJson(packData, SearchDeviceInfo.class);
					Message message = new Message();
					message.obj = searchDeviceInfo;
					sendMessage(message);
					mUdpSocket.close();
					System.out.println("发现设备4" + packData);
				} catch (IOException e) {
					e.printStackTrace();
					mUdpSocket.close();
					System.out.println("发现设备异常");
				}
			}
		}
	}

	private void sendMessage(Message msg) {
		if (mHandler != null) {
			mHandler.sendMessage(msg);
		}
	}

	public boolean stop() {
		if (isRun()) {
			mThread.interrupt();
			try {
				mThread.join();
			} catch (InterruptedException e) {
			}
			return true;
		}
		return false;
	}

	public boolean stopSearch() {
		if (handler != null) {
			handler.removeCallbacks(runnable);
		}
		return false;
	}
}
